#include "topo.h"
#include "pool.h"
#include <iostream>
#include <nlohmann/json.hpp>
#include <fstream>
#include <thread>
extern void cli_loop(Pool& pool);
void RunGrpcServer(const std::string& addr);
extern std::atomic<bool> g_grpc_should_exit;
extern std::condition_variable g_grpc_cv;
extern std::mutex g_grpc_mutex;

Topo* g_topo_ptr = nullptr;
Pool* g_pool_ptr = nullptr;

int main(int argc, char* argv[]) {
    std::string conf_file = "config.json";
    if (argc > 1) conf_file = argv[1];
    Topo topo;
    g_topo_ptr = &topo;
    if (!topo.load_from_json(conf_file)) {
        std::cerr << "配置文件加载失败: " << conf_file << std::endl;
        return 1;
    }
    // 读取EC参数
    std::ifstream in(conf_file);
    nlohmann::json conf;
    in >> conf;
    int ec_data = conf["pool"]["ec_data"];
    int ec_parity = conf["pool"]["ec_parity"];
    Pool pool;
    g_pool_ptr = &pool;
    pool.init(topo, ec_data, ec_parity);
    // 启动gRPC服务端
    std::thread grpc_thread(RunGrpcServer, "0.0.0.0:50050");
    std::cout << "ChunkMaster已启动，输入命令(如: show pool, show pg 0, show topo, show disk 0 0, alloc chunk, exit)" << std::endl;
    cli_loop(pool);
    // 通知gRPC线程退出
    {
        std::lock_guard<std::mutex> lk(g_grpc_mutex);
        g_grpc_should_exit = true;
    }
    g_grpc_cv.notify_one();
    grpc_thread.join();
    return 0;
} 